package com.shouhuobao.bhi.receiver;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.provider.ContactsContract;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.collectplus.express.BaseActivity;
import com.collectplus.express.R;
import com.collectplus.express.city.ChooseAreaActivity;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.ReceiverBean;
import com.collectplus.express.tools.ContactUtils;
import com.umeng.analytics.MobclickAgent;

import droid.frame.utils.lang.Str;
import droid.frame.view.InputFilterExt;

/**
 * 修改包裹
 * 
 * @author coffee<br>
 *         2015-6-24下午4:34:48
 */
public class ReceiverEditActivity extends BaseActivity implements OnClickListener {
	private EditText mNameEdit, mMobileEdit;
	private EditText mAddressEdit, mAddressDetailEdit;
	private Button mOkButton;

	private ReceiverBean receiver;// 包裹

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void findViewById() {
		setContentView(R.layout.receiver_edit);
		super.findViewById();
		setCommonTitle("编辑收件人");
		findViewById(R.id.title_layout).setVisibility(View.VISIBLE);
		//
		mNameEdit = (EditText) findViewById(R.id.receiver_name);
		mMobileEdit = (EditText) findViewById(R.id.receiver_mobile);
		mAddressEdit = (EditText) findViewById(R.id.receiver_address);
		mAddressEdit.setOnClickListener(this);
		mAddressDetailEdit = (EditText) findViewById(R.id.receiver_address_detail);

		mMobileEdit.setFilters(new InputFilter[] { new InputFilterExt(1) });

		mOkButton = (Button) findViewById(R.id.receiver_edit_sure);
		mOkButton.setText("确认");
		mOkButton.setOnClickListener(this);

		// 调用系统通讯录
		findViewById(R.id.receiver_contact).setOnClickListener(this);

		receiver = (ReceiverBean) getIntent().getSerializableExtra("item");

		setTextAndTag(mNameEdit, receiver.getName());
		// 光标移动到最后
		setCursorToLast(mNameEdit);

		String phone = Str.formatPhone(receiver.getPhone());
		setTextAndTag(mMobileEdit, phone);
		String address = receiver.getProvince() + "  " + receiver.getCity() + "  " + receiver.getDistrict();
		setTextAndTag(mAddressEdit, address);
		setTextAndTag(mAddressDetailEdit, receiver.getAddress());

		findViewById(R.id.receiver_shot).setOnClickListener(this);
	}

	/**
	 * 设置tag用来校验数据是否被修改
	 * 
	 * @param editText
	 * @param text
	 */
	private void setTextAndTag(EditText editText, String text) {
		editText.setText(text);
		editText.setTag(editText.getText().toString());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.receiver_shot:
			Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(intent, 1003);
			break;
		// 选取地址
		case R.id.receiver_address:
			Intent i = new Intent(getContext(), ChooseAreaActivity.class);
			startActivityForResult(i, 101);
			break;
		// 从通讯录中添加
		case R.id.receiver_contact:
			intent = new Intent();
			intent.setAction(Intent.ACTION_PICK);
			intent.setData(ContactsContract.Contacts.CONTENT_URI);
			startActivityForResult(intent, 102);
			break;
		// 确认
		case R.id.receiver_edit_sure:
			String name = mNameEdit.getText().toString();
			String phone = mMobileEdit.getText().toString();
			String address = mAddressDetailEdit.getText().toString();
			if (TextUtils.isEmpty(name)) {
				showToast("请输入收件人姓名");
				return;
			}
			if (name.indexOf(' ') > 0) {
				showToast("姓名不能输入特殊字符");
				return;
			}
			if (TextUtils.isEmpty(phone.trim())) {
				showToast("请输入收件人手机号");
				return;
			}
			// if ((phone.trim().length() != 11) && (phone.trim().length() != 12)) {
			// showToast("请输入正确的手机号");
			// return;
			// }
			if (TextUtils.isEmpty(address)) {
				showToast("请输入收件人详细地址");
				return;
			}
			showLoadingDialog(null);
			receiver.setName(mNameEdit.getText().toString());
			receiver.setPhone(mMobileEdit.getText().toString());
			receiver.setAddress(mAddressDetailEdit.getText().toString());
			int userId = AppCache.getUserId();
			// 本地 数据
			if (userId == 0 || receiver.getId() == 0 || AppCache.getOrder() == null) {
				setActivityResult();
			} else {
				// 调用老接口
				AppHttp.getInstance().receiverEditOld(receiver.getId(), name.trim(), phone, //
						receiver.getProvinceId(), receiver.getCityId(), receiver.getDistrictId(), address);
			}
			break;
		}
	}

	private void setActivityResult() {
		// 数据是否被修改
		boolean modify = true;
		if (mNameEdit.getText().toString().equals(mNameEdit.getTag()) //
				&& mMobileEdit.getText().toString().equals(mMobileEdit.getTag()) //
				&& mAddressEdit.getText().toString().equals(mAddressEdit.getTag()) //
				&& mAddressDetailEdit.getText().toString().equals(mAddressDetailEdit.getTag())) { //
			modify = false;
		}
		Intent data = new Intent();
		data.putExtra("item", receiver);
		data.putExtra("modify", modify);
		setResult(Activity.RESULT_OK, data);
		finish();
	}

	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MsgID.receiverEdit:
			cancelLoadingDialog();
			AppResult<?> result = JSON.parser(msg.obj);
			switch (result.getStatus()) {
			case 1:
				setActivityResult();
				break;
			case 0:
				showToast(result.getMessage());
				break;
			}
			return true;
		default:
			return super.handleMessage(msg);
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// 修改地址
		if (resultCode == Activity.RESULT_OK && requestCode == 101) {
			ReceiverBean tmp = (ReceiverBean) data.getSerializableExtra("item");
			mAddressEdit.setText(tmp.getProvince() + " " + tmp.getCity() + " " + tmp.getDistrict());
			receiver.setProvince(tmp.getProvince());
			receiver.setProvinceId(tmp.getProvinceId());
			receiver.setCity(tmp.getCity());
			receiver.setCityId(tmp.getCityId());
			receiver.setDistrict(tmp.getDistrict());
			receiver.setDistrictId(tmp.getDistrictId());
		}
		// 手机通讯录
		else if (resultCode == Activity.RESULT_OK && requestCode == 102) {
			if (data == null) {
				return;
			}
			try {
				// content://com.android.contacts/contacts/lookup/1885r7-45D643445A61896E3D23/7
				String[] phones = new ContactUtils().getContactPhone(getContext(), data.getData());
				mNameEdit.setText(phones[0]);
				mMobileEdit.setText(phones[1]);
				//
				MobclickAgent.onEvent(getContext(), "联系人From通讯录");
			} catch (Exception e) {
				e.printStackTrace();
				showToast("获取联系人失败");
			}
		}
	}
}
